import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;

/**
 * Builds and maintains a list of stop words.
 * @author gabriel
 *
 */
public class StopWordList {

    /**
     * A string representing the overridden breaks
     */
    private String breaks;
    
    /**
     * A set of stop words
     */
    private HashSet stopSet;
    
    /**
     * Indicates any errors that happened
     */
    private String errorMessage = "";
    
    /**
     * Initializes this object 
     * @param overriddenBreaks The breaks to override
     */
    public StopWordList(String overriddenBreaks) {
        this.breaks = overriddenBreaks;
        this.stopSet = new HashSet();
    }
    
    /**
     * Initializes this object with no overridden breaks
     *
     */
    public StopWordList() {
        this("");
    }

    /**
     * Builds the stopword list from the file specified by user
     * @param fileName the file to parse stop words from
     * @return true on success
     * @throws IOException
     */
    public boolean parseFile(String fileName) throws QUIRKException {
        /* Open file */
        InputStream fileInput;
        try {
			fileInput = new FileInputStream(fileName);
		} catch (FileNotFoundException e) {
			throw new QUIRKException(QUIRKException.CANNOT_READ_STOP_WORD_FILE);
		}
        BufferedInputStream stream = new BufferedInputStream(fileInput);
        /* Delegate to other version to perform Histogram */
        WordTokenizer tok = new WordTokenizer(stream, breaks);
        if (!tok.breaksAreValid()) {
            errorMessage = tok.getErrorMessage();
            return false;
        }
        String token;
        try {
			while ((token = tok.nextToken()) != null) {
			    token = token.toLowerCase();
			    this.stopSet.add(token);
			}
		} catch (IOException e) {
			throw new QUIRKException(QUIRKException.CANNOT_PROCESS_STOP_WORD_FILE);
		}
        try {
			fileInput.close();
		} catch (IOException e) {
			throw new QUIRKException(QUIRKException.CANNOT_PROCESS_STOP_WORD_FILE);
		}
        return true;
    }
    
    /**
     * Tests if a word is in the stop list
     * @param word Word to test
     * @return true if the word is a stop word, otherwise false
     */
    public boolean isStop(String word) {
        return this.stopSet.contains(word);
    }

    /**
     * @return Returns the errorMessage.
     */
    public String getErrorMessage() {
        return errorMessage;
    }
    
}
